'use strict'
import Vue from 'vue'
import Vuex from 'vuex'
import RoomManage from './roommanage'
// 告诉 vue “使用” vuex
Vue.use(Vuex)
Vue.use(RoomManage)
// 创建一个对象来保存应用启动时的初始状态
const state = {
  // TODO: 放置初始状态
  navShow: true,
  rooms: [],
  historyRooms: [],
  delRoomConfirm: {
    show: false,
    index: -1,
    roomId: '0',
    platform: ''
  },
  rightDrawer: {
    showRank: false,
    showMsg: false,
    key: '0',
    el: null,
    msgs: [],
    opts: [{
      value: 'msgs',
      text: '弹幕总榜'
    }, {
      value: 'gifts',
      text: '礼物总榜'
    }],
    items: []
  },
  addroom: {
    indicator: {
      show: false,
      type: 'toast',
      opactiy: 0.2,
      text: '连接中...'
    },
    toasts: []
  }
}

// 创建一个对象存储一系列我们接下来要写的 mutation 函数
const mutations = {
  // TODO: 放置我们的状态变更函数
  SHOWNAV (state, isShow) {
    state.navShow = isShow
  },
  ADDROOM (state, platform, roomId, fn) {
    if (roomId !== '' && /^[0-9a-zA-Z]*$/.test(roomId.toLowerCase().trim())) {
      state.addroom.indicator.show = true
      setTimeout(() => { state.addroom.indicator.show = false }, 5000)
      Vue.prototype.$RoomManage.addRoom(platform, roomId, (result) => {
        if (fn) {
          fn(result.code)
        }
        if (result.code !== 0) {
          state.addroom.toasts.push({
            text: result.code === -1 ? '没找到直播间' : '重复监控'
          })
          setTimeout(() => state.addroom.toasts.splice(0, 1), 2000)
        } else {
          state.rooms.push(result.data)
          state.addroom.toasts.push({
            text: '成功监控'
          })
          setTimeout(() => state.addroom.toasts.splice(0, 1), 2000)
        }
        state.addroom.indicator.show = false
      })
    } else {
      this.toasts.push({
        text: '请输入直播间ID或别名'
      })
      setTimeout(() => this.toasts.splice(0, 1), 2000)
    }
  },
  GETROOMS (state) {
    Vue.prototype.$RoomManage.getRooms((obj) => {
      let rooms = obj.rooms
      for (var i = 0; i < rooms.length; i++) {
        state.rooms.push(rooms[i])
      }
    })
  },
  REMOVEROOM (state) {
    Vue.prototype.$RoomManage.remove(state.delRoomConfirm.platform, state.delRoomConfirm.roomId)
    state.rooms.splice(state.delRoomConfirm.index, 1)
  },
  SHOWDELROOMCONFIRM (state, isShow, index, platform, roomId) {
    state.delRoomConfirm.show = isShow
    state.delRoomConfirm.index = index
    state.delRoomConfirm.roomId = roomId
    state.delRoomConfirm.platform = platform
  },
  SHOWMSG (state, key) {
    state.rightDrawer.showMsg = key !== state.rightDrawer.key || state.rightDrawer.showRank
    state.rightDrawer.showRank = false
    state.rightDrawer.key = state.rightDrawer.showMsg ? key : ''
  },
  SHOWRANK (state, key) {
    state.rightDrawer.showRank = key !== state.rightDrawer.key || state.rightDrawer.showMsg
    state.rightDrawer.showMsg = false
    state.rightDrawer.key = state.rightDrawer.showRank ? key : ''
  },
  RIGHTDRAWERCLOSE () {
    state.rightDrawer.showRank = false
    state.rightDrawer.showMsg = false
    state.rightDrawer.key = ''
  },
  INITMSGS (state) {
    state.rightDrawer.msgs = []
    let room = Vue.prototype.$RoomManage.getRoom(state.rightDrawer.key)
    if (room) {
      for (var i = 0; i < room.chatMessages.length; i++) {
        state.rightDrawer.msgs.push(room.chatMessages[i])
      }
      setTimeout(() => {
        state.rightDrawer.el.scrollTo = state.rightDrawer.el.offsetHeight
      }, 500)
    }
    Vue.prototype.$RoomManage.off('chat')
    Vue.prototype.$RoomManage.on('chat', (msg) => {
      let key = msg.platform.concat('_').concat(msg.rid)
      if (state.rightDrawer.key === key) {
        if (state.rightDrawer.msgs.length >= 200) {
          state.rightDrawer.msgs.splice(0, 100)
        }
        state.rightDrawer.msgs.push(msg)
        state.rightDrawer.el.scrollTop = state.rightDrawer.el.scrollHeight - state.rightDrawer.el.offsetHeight
      }
    })
  },
  BINDMSGS (state, el) {
    state.rightDrawer.el = el
  },
  INITGIFT (state, platform) {
    state.rightDrawer.opts = state.rightDrawer.opts.slice(0, 2)
    state.rightDrawer.opts.push({
      value: 'coins',
      text: platform === 'dy' ? '鱼翅总榜' : '猫币总榜'
    })
    Vue.prototype.$RoomManage.getGift(state.rightDrawer.key, (result) => {
      let gifts = result.gifts
      if (gifts) {
        gifts.forEach((item) => {
          state.rightDrawer.opts.push(item)
        })
      }
    })
  },
  GETRANK (state, field) {
    state.rightDrawer.items = []
    Vue.prototype.$RoomManage.getRank(state.rightDrawer.key, field, (result) => {
      let users = result.ranks
      if (users) {
        for (var i = 0; i < users.length; i++) {
          if (users[i]) {
            const {uid, ic, level, nn} = users[i]
            state.rightDrawer.items.push({
              uid,
              ic,
              level,
              nn,
              'date': getLastTime(users[i], field),
              'value': (field === 'coins' ? users[i][field].toFixed(1) : users[i][field])
            })
          }
        }
      }
    })
    function getLastTime (user, field) {
      if (user.hasOwnProperty(field + '_lastTime')) {
        var time = user[field + '_lastTime']
        if (time) {
          if (field === 'msgs') {
            return '最后时间[' + user[field + '_lastTime'] + ']'
          } else {
            return '赠送时间[' + user[field + '_lastTime'] + ']'
          }
        }
        return time
      }
      return ''
    }
  },
  GETHISTORYROOM (state) {
    state.historyRooms = []
    Vue.prototype.$RoomManage.getHistoryRoom((items) => {
      for (var key in items) {
        if (items.hasOwnProperty(key)) {
          let room = items[key]
          room.isWatch = Vue.prototype.$RoomManage.hasRoom(room.platform, room.roomId)
          state.historyRooms.push(room)
        }
      }
    })
  },
  REMOVEHISTORYROOM (state, key, index) {
    state.historyRooms.splice(index, 1)
    Vue.prototype.$RoomManage.removeHistoryRoom(key)
  }
}

// 整合初始状态和变更函数，我们就得到了我们所需的 store
// 至此，这个 store 就可以连接到我们的应用中
export default new Vuex.Store({
  state,
  mutations})
